package com.ciaojian.client.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ciaojian.client.service.OrderServiceImpl;
import com.ciaojian.client.service.PhoneCreditServiceImpl;
import com.ciaojian.core.config.FuluOpenConfig;
import com.ciaojian.core.mapper.CouponCodeMapper;
import com.ciaojian.core.mapper.DFulugoodsMapper;
import com.ciaojian.core.mapper.OrderMapper;
import com.ciaojian.core.mapper.PhoneCreditMapper;
import com.ciaojian.core.model.*;
import com.ciaojian.core.model.fulu.*;
import com.ciaojian.core.model.vo.PhoneCreditVo;
import com.ciaojian.core.util.FuluUtil;
import com.ciaojian.core.util.JsonUtil;
import com.ciaojian.core.util.LogUtil;
import com.ciaojian.core.util.Result;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author cano
 */
@Api(tags = "福禄 -> 话费充值")
@RestController
@Slf4j
@RequestMapping("/mobileCharge")
public class FuluMobileCharge {


    @Autowired
    private PhoneCreditServiceImpl phoneCreditService;
    @Resource
    private PhoneCreditMapper phoneCreditMapper;
    @Autowired
    private OrderServiceImpl orderService;
    @Resource
    private CouponCodeMapper couponCodeMapper;
    @Resource
    private DFulugoodsMapper dFulugoodsMapper;
    @Resource
    private OrderMapper orderMapper;


    /**
     * postman调用 ,已经写了定时
     * @return
     */
    @ApiOperation("商品列表")
    @ApiResponses({@ApiResponse(code = 200, message = "success", response = MemberDetail.class)})
    @GetMapping("/goodsList")
    public List<FuluGoodsList>  goodsList() {

        String d = "{\"first_category_id\": \"\",}";
        FuluRequest fuluRequest = FuluUtil.newFuluRequest(d, FuluOpenConfig.GOODSLIST_GET_METHOD,FuluOpenConfig.APP_KEY,FuluOpenConfig.SYSSECRET);
        String fuluRequestJson = JsonUtil.toJson(fuluRequest);
        String fuluResponseJson = HttpUtil.post(FuluOpenConfig.FULU_PROD_URL, fuluRequestJson);
        FuluGoods fuluGoods = JsonUtil.fromJson(fuluResponseJson, FuluGoods.class);
        String result = fuluGoods.getResult();
        Gson gson = new GsonBuilder().create();
        List<FuluGoodsList> fuluGoodsLists = gson.fromJson(result, new TypeToken<List<FuluGoodsList>>() {}.getType());


        for (FuluGoodsList fuluGoodsList : fuluGoodsLists) {

            QueryWrapper<DFulugoods> fgqw = new QueryWrapper<>();
            fgqw.eq("fulu_goods_id", fuluGoodsList.getProduct_id());
            DFulugoods dFulugoods = dFulugoodsMapper.selectOne(fgqw);
            if (ObjectUtil.isNotNull(dFulugoods)){
                dFulugoods.setGoodsTitle(fuluGoodsList.getProduct_name());
                dFulugoods.setGoodsType(fuluGoodsList.getProduct_type());
                dFulugoods.setFaceValue(fuluGoodsList.getFace_value());
                dFulugoods.setPurchasePrice(fuluGoodsList.getPurchase_price());
                dFulugoods.setUpdateTime(new Date());
                switch (fuluGoodsList.getStock_status()) {
                    case "充足":
                        dFulugoods.setStockStatus(0);
                        break;
                    case "断货":
                        dFulugoods.setStockStatus(1);
                        break;
                    case "警报":
                        dFulugoods.setStockStatus(2);
                        break;
                    default:
                        break;
                }

                switch (fuluGoodsList.getSales_status()) {
                    case "上架":
                        dFulugoods.setFuluStatus(0);
                        break;
                    case "下架":
                        dFulugoods.setFuluStatus(1);
                        break;
                    case "维护中":
                        dFulugoods.setFuluStatus(2);
                        break;
                    case "库存维护":
                        dFulugoods.setFuluStatus(3);
                        break;
                    default:
                        break;
                }
                dFulugoodsMapper.updateById(dFulugoods);
            }else {

                DFulugoods dFulugoodsNew = new DFulugoods();
                dFulugoodsNew.setFuluGoodsId(fuluGoodsList.getProduct_id());
                dFulugoodsNew.setGoodsTitle(fuluGoodsList.getProduct_name());
                dFulugoodsNew.setGoodsType(fuluGoodsList.getProduct_type());
                dFulugoodsNew.setFaceValue(fuluGoodsList.getFace_value());
                dFulugoodsNew.setPurchasePrice(fuluGoodsList.getPurchase_price());
                dFulugoodsNew.setUpdateTime(new Date());
                switch (fuluGoodsList.getStock_status()) {
                    case "充足":
                        dFulugoodsNew.setStockStatus(0);
                        break;
                    case "断货":
                        dFulugoodsNew.setStockStatus(1);
                        break;
                    case "警报":
                        dFulugoodsNew.setStockStatus(2);
                        break;
                    default:
                        break;
                }

                switch (fuluGoodsList.getSales_status()) {
                    case "上架":
                        dFulugoodsNew.setFuluStatus(0);
                        break;
                    case "下架":
                        dFulugoodsNew.setFuluStatus(1);
                        break;
                    case "维护中":
                        dFulugoodsNew.setFuluStatus(2);
                        break;
                    case "库存维护":
                        dFulugoodsNew.setFuluStatus(3);
                        break;
                    default:
                        break;
                }

                dFulugoodsMapper.insert(dFulugoodsNew);
            }
        }


        return fuluGoodsLists;
    }

    @ApiOperation("商品信息回调接口")
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/fuluGoodsNotify")
    public void fuluNotify(@RequestBody FuluGoodsNotify fuluGoodsNotify) {
        log.info("##fuluGoods##->>"+
                "productId:"+fuluGoodsNotify.getProduct_id());
        //直接全表查寻福禄 同步信息
        String d = "{\"first_category_id\": \"\",}";
        FuluRequest fuluRequest = FuluUtil.newFuluRequest(d, FuluOpenConfig.GOODSLIST_GET_METHOD,FuluOpenConfig.APP_KEY,FuluOpenConfig.SYSSECRET);
        String fuluRequestJson = JsonUtil.toJson(fuluRequest);
        String fuluResponseJson = HttpUtil.post(FuluOpenConfig.FULU_PROD_URL, fuluRequestJson);
        FuluGoods fuluGoods = JsonUtil.fromJson(fuluResponseJson, FuluGoods.class);

        String result = fuluGoods.getResult();
        Gson gson = new GsonBuilder().create();
        List<FuluGoodsList> fuluGoodsLists = gson.fromJson(result, new TypeToken<List<FuluGoodsList>>() {}.getType());


        for (FuluGoodsList fuluGoodsList : fuluGoodsLists) {

            QueryWrapper<DFulugoods> fgqw = new QueryWrapper<>();
            fgqw.eq("fulu_goods_id", fuluGoodsList.getProduct_id());
            DFulugoods dFulugoods = dFulugoodsMapper.selectOne(fgqw);

            if (ObjectUtil.isNotNull(dFulugoods)){
                dFulugoods.setGoodsTitle(fuluGoodsList.getProduct_name());
                dFulugoods.setGoodsType(fuluGoodsList.getProduct_type());
                dFulugoods.setFaceValue(fuluGoodsList.getFace_value());
                dFulugoods.setPurchasePrice(fuluGoodsList.getPurchase_price());
                dFulugoods.setUpdateTime(new Date());
                switch (fuluGoodsList.getStock_status()) {
                    case "充足":
                        dFulugoods.setStockStatus(0);
                        break;
                    case "断货":
                        dFulugoods.setStockStatus(1);
                        break;
                    case "警报":
                        dFulugoods.setStockStatus(2);
                        break;
                    default:
                        break;
                }

                switch (fuluGoodsList.getSales_status()) {
                    case "上架":
                        dFulugoods.setFuluStatus(0);
                        break;
                    case "下架":
                        dFulugoods.setFuluStatus(1);
                        break;
                    case "维护中":
                        dFulugoods.setFuluStatus(2);
                        break;
                    case "库存维护":
                        dFulugoods.setFuluStatus(3);
                        break;
                    default:
                        break;
                }
                dFulugoodsMapper.updateById(dFulugoods);
            }else {

                DFulugoods dFulugoodsNew = new DFulugoods();
                dFulugoodsNew.setFuluGoodsId(fuluGoodsList.getProduct_id());
                dFulugoodsNew.setGoodsTitle(fuluGoodsList.getProduct_name());
                dFulugoodsNew.setGoodsType(fuluGoodsList.getProduct_type());
                dFulugoodsNew.setFaceValue(fuluGoodsList.getFace_value());
                dFulugoodsNew.setPurchasePrice(fuluGoodsList.getPurchase_price());
                dFulugoodsNew.setUpdateTime(new Date());
                switch (fuluGoodsList.getStock_status()) {
                    case "充足":
                        dFulugoodsNew.setStockStatus(0);
                        break;
                    case "断货":
                        dFulugoodsNew.setStockStatus(1);
                        break;
                    case "警报":
                        dFulugoodsNew.setStockStatus(2);
                        break;
                    default:
                        break;
                }

                switch (fuluGoodsList.getSales_status()) {
                    case "上架":
                        dFulugoodsNew.setFuluStatus(0);
                        break;
                    case "下架":
                        dFulugoodsNew.setFuluStatus(1);
                        break;
                    case "维护中":
                        dFulugoodsNew.setFuluStatus(2);
                        break;
                    case "库存维护":
                        dFulugoodsNew.setFuluStatus(3);
                        break;
                    default:
                        break;
                }

                dFulugoodsMapper.insert(dFulugoodsNew);
            }
        }



        QueryWrapper<DFulugoods> fgqw = new QueryWrapper<>();
        fgqw.eq("fulu_goods_id", fuluGoodsNotify.getProduct_id());
        DFulugoods dFulugoods = dFulugoodsMapper.selectOne(fgqw);

        if (fuluGoodsNotify.getChanged_type()==1){
            switch (fuluGoodsNotify.getProduct_sale_status()) {
                case "上架":
                    dFulugoods.setFuluStatus(0);
                    break;
                case "下架":
                    dFulugoods.setFuluStatus(1);
                    break;
                default:
                    break;
            }
            dFulugoodsMapper.updateById(dFulugoods);
        }

        if (fuluGoodsNotify.getChanged_type()==2){
            dFulugoods.setPurchasePrice(fuluGoodsNotify.getProduct_price());
            dFulugoodsMapper.updateById(dFulugoods);
        }
    }


    @ApiOperation("话费充值  影视会员充值")
    @ApiResponses({@ApiResponse(code = 200, message = "success", response = MemberDetail.class)})
    @PostMapping("/top-up")
    public Result requestFuluMoblieAdd(@RequestBody PhoneCreditVo phoneCreditVo) {
        Assert.isTrue(ObjectUtil.isNotNull(phoneCreditVo.getUserPhone()), "请填入充值账号");
        if (ObjectUtil.isNull(phoneCreditVo.getUserPhone())|| "".equals(phoneCreditVo.getUserPhone())){
            return Result.error("请输入正确的充值账号");
        }
        return phoneCreditService.requestFuluMoblieAdd(phoneCreditVo);
    }

    @ApiOperation("话费充值  影视会员充值 (后台)")
    @ApiResponses({@ApiResponse(code = 200, message = "success", response = MemberDetail.class)})
    @PostMapping("/admin-up")
    public Result adminFuluMoblieAdd(@RequestBody PhoneCreditVo phoneCreditVo) {
        Assert.isTrue(ObjectUtil.isNotNull(phoneCreditVo.getUserPhone()), "请填入充值账号");
        if (ObjectUtil.isNull(phoneCreditVo.getUserPhone())|| "".equals(phoneCreditVo.getUserPhone())){
            return Result.error("请输入正确的充值账号");
        }
        return phoneCreditService.adminFuluMoblieAdd(phoneCreditVo);
    }


    @ApiOperation("话费充值回调接口")
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/fuluNotify")
    public String fuluNotify(@RequestBody FuluNotify fuluNotify) {
        try {
            String news = null;
            if (fuluNotify.getOrder_status().equals("success")) {
                news = "s";
            } else {
                news = "f";
            }
            log.info(news + "o:" + fuluNotify.getOrder_id());
            LogUtil.writeBusinessLog(news + "o:" + fuluNotify.getOrder_id()+"::"+fuluNotify.getRecharge_description());

            if (fuluNotify.getOrder_status().equals("success")) {

                QueryWrapper<PhoneCredit> phoneCreditQueryWrapper = new QueryWrapper<>();
                phoneCreditQueryWrapper.eq("trade_no", fuluNotify.getOrder_id());
                PhoneCredit phoneCredit = phoneCreditMapper.selectOne(phoneCreditQueryWrapper);
                phoneCredit.setStatus(1);
                phoneCredit.setRechargeTime(new Date());
                phoneCredit.setTradeNo(fuluNotify.getOrder_id());
                int chengePC = phoneCreditMapper.updateById(phoneCredit);

                //修改成功
                if (chengePC > 0) {
                    return "success";
                }
            } else {
                QueryWrapper<PhoneCredit> phoneCreditQueryWrapper = new QueryWrapper<>();
                phoneCreditQueryWrapper.eq("trade_no", fuluNotify.getOrder_id());
                PhoneCredit phoneCredit = phoneCreditMapper.selectOne(phoneCreditQueryWrapper);
                phoneCredit.setStatus(0);
                phoneCredit.setTradeNo(fuluNotify.getOrder_id());
                phoneCreditMapper.updateById(phoneCredit);
                return "success";
            }
        }catch (Exception e){
            LogUtil.writeBusinessLog("fuluNotify:"+fuluNotify.getOrder_id()+": {}", e.getMessage());
        }

        return "success";
    }


    /**
     * postman查订单
     * @param orderNo
     * @return
     */
    @ApiOperation("查询订单接口")
    @Transactional(rollbackFor = Exception.class)
    @GetMapping("/getOrder")
    public Result getOrder(@RequestParam String orderNo) {
        String orderJson = "{\"customer_order_no\": \""+orderNo+"\"}";
        FuluRequest fuluRequest = FuluUtil.newFuluRequest(orderJson,FuluOpenConfig.ORDERINFO_GET_METHOD,FuluOpenConfig.APP_KEY,FuluOpenConfig.SYSSECRET);
        String fuluRequestJson = JsonUtil.toJson(fuluRequest);
        String fuluResponseJson = HttpUtil.post(FuluOpenConfig.FULU_PROD_URL, fuluRequestJson);
        FuluResponse fuluResponse = JsonUtil.fromJson(fuluResponseJson, FuluResponse.class);

        OrderInfo orderInfo = JsonUtil.fromJson(fuluResponse.getResult(), OrderInfo.class);

        return Result.ok(orderInfo);
    }

    /**
     * postman查订单
     * @param orderNo
     * @return
     */
    @ApiOperation("查询订单接口")
    @Transactional(rollbackFor = Exception.class)
    @GetMapping("/getOrderInfo")
    public Result getOrderInfo(@RequestParam String code) {
        QueryWrapper<PhoneCredit> qw = new QueryWrapper<>();
        qw.eq("code",code);
        PhoneCredit phoneCredit = phoneCreditMapper.selectOne(qw);
        if (ObjectUtil.isNotNull(phoneCredit)&& phoneCredit.getStatus()==1){
            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setOrder_state("success");
            return Result.ok(orderInfo);
        }

        Assert.isTrue(ObjectUtil.isNotEmpty(phoneCredit), "未找到该券码");

        Order order = orderService.getById(phoneCredit.getOrderId());

        String orderJson = "{\"customer_order_no\": \""+order.getOrderNo()+"\"}";
        FuluRequest fuluRequest = FuluUtil.newFuluRequest(orderJson,FuluOpenConfig.ORDERINFO_GET_METHOD,FuluOpenConfig.APP_KEY,FuluOpenConfig.SYSSECRET);
        String fuluRequestJson = JsonUtil.toJson(fuluRequest);
        String fuluResponseJson = HttpUtil.post(FuluOpenConfig.FULU_PROD_URL, fuluRequestJson);

        FuluResponse fuluResponse = JsonUtil.fromJson(fuluResponseJson, FuluResponse.class);

        OrderInfo orderInfo = JsonUtil.fromJson(fuluResponse.getResult(), OrderInfo.class);
        if (ObjectUtil.isNull(orderInfo)){
            return Result.error("请稍后");
        }
        if (phoneCredit.getStatus()!=1) {
            if (orderInfo.getOrder_state().equals("success")) {
                phoneCredit.setTradeNo(orderInfo.getOrder_id());
                phoneCredit.setStatus(1);

                QueryWrapper<CouponCode> couponCodeQueryWrapper = new QueryWrapper<>();
                couponCodeQueryWrapper.eq("outside_code",phoneCredit.getCode());
                CouponCode couponCode = couponCodeMapper.selectOne(couponCodeQueryWrapper);
                couponCode.setStatus(2);
                phoneCreditMapper.updateById(phoneCredit);
                couponCodeMapper.updateById(couponCode);
            }

            if (orderInfo.getOrder_state().equals("processing")||orderInfo.getOrder_state().equals("untreated")) {
                phoneCredit.setTradeNo(orderInfo.getOrder_id());
                phoneCredit.setStatus(2);
                phoneCreditMapper.updateById(phoneCredit);
            }

            if (orderInfo.getOrder_state().equals("failed")) {
                phoneCredit.setTradeNo(orderInfo.getOrder_id());
                phoneCredit.setStatus(0);
                phoneCreditMapper.updateById(phoneCredit);
            }
        }

        return Result.ok(orderInfo);
    }


    /**
     * postman查产品
     * @param orderNo
     * @return
     */
    @ApiOperation("商品信息")
    @ApiResponses({@ApiResponse(code = 200, message = "success", response = MemberDetail.class)})
    @GetMapping("/shop_id")
    public Result goodsInfo(String productId) {

        String productJson = "{\"product_id\": \""+productId+"\"}";

        FuluRequest fuluRequest = FuluUtil.newFuluRequest(productJson, FuluOpenConfig.GOODSINFO_GET_METHOD,FuluOpenConfig.APP_KEY,FuluOpenConfig.SYSSECRET);
        String fuluRequestJson = JsonUtil.toJson(fuluRequest);
        String fuluResponseJson = HttpUtil.post(FuluOpenConfig.FULU_PROD_URL, fuluRequestJson);
        return Result.ok(fuluResponseJson);
    }

    /**
     * postman查商品
     * @param orderNo
     * @return
     */
    @ApiOperation("商品模板")
    @ApiResponses({@ApiResponse(code = 200, message = "success", response = MemberDetail.class)})
    @GetMapping("/shop_template")
    public Result goodsTemplate(String templateId) {

        String productJson = "{\"template_id\": \""+templateId+"\"}";

        FuluRequest fuluRequest = FuluUtil.newFuluRequest(productJson, FuluOpenConfig.GOODSTEMPLATE_GET_METHOD,FuluOpenConfig.APP_KEY,FuluOpenConfig.SYSSECRET);
        String fuluRequestJson = JsonUtil.toJson(fuluRequest);
        String fuluResponseJson = HttpUtil.post(FuluOpenConfig.FULU_PROD_URL, fuluRequestJson);
        return Result.ok(fuluResponseJson);
    }

}
